<?php

/**
 * Description of x10_TraceInfoManager
 *
 * @author prometheus
 */
class x10_TraceInfoManager extends x10_Manager
{
	public $xName = 'Követési információk kezelője';
	
	public $enable = TRUE;

	public $logPath = '';

	public $recordLimit = 150;
	
	/**
	 * Konstruktor.
	 * @param x10_Config $config
	 * @throws x10_E_Observer_ObservedObjectIsNotObject
	 * @throws x10_E_Observer_ObservedObjectUndefined
	 */
	public function __construct(x10_Config $config=NULL)
	{
		parent::__construct($config);
		$this->registerProvider(new x10_Provider_Descriptor('x10_TraceInfoManager_InfoProvider'));
		
		$this->logPath = x10::$systemRoot.$this->config->getConfigKey('logPath');
		$rl = $this->config->getConfigKey('recordLimit');
		if (isset($rl)) $this->recordLimit = $rl;
		$en = $this->config->getConfigKey('enable');
		if (isset($en)) $this->enable = $en;

		x10::ifDedicated($this);
		x10::dedicate($this);
	}

	/**
	 * @param String $className
	 * @return x10_Config
	 */
	protected function createProviderConfig($className)
	{
		$castedName = array_pop($c = explode('_', $className));
		if (file_exists($this->logPath.$castedName.'.log.json'))
		{
			$logs = new x10_Util_JSON('file://'.$this->logPath.$castedName.'.log.json', TRUE);
		}
		$cfg = array(
			'castedName'	=> $castedName,
			'logs'			=> (isset($logs)? $logs->get() : NULL),
			'recordLimit'	=> $this->recordLimit
		);

		return new x10_Config($cfg);
	}

	/**
	 * Létrehoz és regisztrál egy log szolgáltatót. Ha a szolgáltató már létezik,
	 * a létezővel tér vissza.
	 * @param String $providerClass
	 * @return x10_TraceInfoManager_InfoProvider
	 */
	public function setupProvidrer($providerClass)
	{
		$result = NULL;
		if (isset($this[$providerClass]))
		{
			$result = $this[$providerClass];
		}
		else
		{
			$result = new $providerClass($this->createProviderConfig($providerClass));
			$this[$providerClass] = $result;
		}
		return $result;
	}

	/**
	 * Eltárolja a nyomkövetési információkat.
	 */
	public function storeLogs()
	{
		if (!$this->enable) return;
		
		foreach ((array)$this as $name=>$prov)
		{
			$logdata = (string)$prov;
			if (!file_exists($this->logPath) or !is_dir($this->logPath))
			{
				mkdir($this->logPath, 0777, TRUE);
				chmod($this->logPath, 0777);
			}
			if (file_exists($this->logPath))
			{
				file_put_contents($this->logPath.$name.'.log.json', $logdata);
			}
		}
	}
}

?>